package lx.prac.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.Properties;
import java.util.regex.Pattern;

public class ConsumerOne {
    private static Logger logger = LoggerFactory.getLogger(ConsumerOne.class);

    public static void main(String[] args){
        KafkaConsumer<String,String> consumer = getConsumerOne();
        consumer.subscribe(Pattern.compile("my-.*"));

        try {
            while (true) {
                logger.info("**********************************loop begin**********************************");
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
                for (ConsumerRecord<String, String> item : records) {
                    logger.info("one record begin...");
                    logger.info("topic:" + item.topic() + ",partition:" + item.partition() + ",offset:" + item.offset() + ",customer:" + item.offset() + ",value:" + item.value());
                }
                Thread.sleep(5000);

            }
        } catch (InterruptedException e) {
            logger.error(e.getMessage(),e);
        } finally {
            consumer.close();
            logger.info("consume closed...");
        }
    }

    private static <T,V> KafkaConsumer getConsumerOne() {
        Properties p = new Properties();
        p.put("bootstrap.servers", "10.211.55.22:9091,10.211.55.22:9093");
        p.put("group.id", "my-group");
        p.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        p.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        p.put("auto.commit.offset", false);

        return new KafkaConsumer<T,V>(p);
    }
}
